package com.qf.openapi.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Component
@Slf4j
public class ParamFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        // 尊重前面过滤器的判断结果
        RequestContext currentContext = RequestContext.getCurrentContext();
        boolean b = currentContext.sendZuulResponse();

        return b;
    }

    @Override
    public Object run() throws ZuulException {

        //1. 获取必传参数集合
        Set<String> systemParamSet = getParamSet();

        //2. 获取请求中所有携带的参数的集合
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        Set<String> rquestParamSet = request.getParameterMap().keySet();

        //3. 判断是不是所有必传参数都传了
        systemParamSet.removeAll(rquestParamSet);

        if (systemParamSet!=null&&systemParamSet.size()>0){
            log.info("必传参数缺少了，{}",systemParamSet);
            // 不要请求继续发给后面的微服务了
            currentContext.setSendZuulResponse(false);
            HttpServletResponse response = currentContext.getResponse();
            response.setContentType("text/html;charset=utf-8");
            try {
                response.getWriter().println("必传参数缺少了:"+systemParamSet);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return null;
        }
        log.info("必传参数检查通过了");
        return null;
    }

    private Set<String> getParamSet() {
        HashSet<String> set = new HashSet<>();
        set.add("apiname");
        set.add("sign");
        set.add("customerkey"); // 代表当前请求是哪个客户发送的

        return set;
    }
}
